package controller

import (
	"60321/pkg/global"
	"60321/pkg/models"
	"60321/pkg/models/requests"
	"60321/pkg/tokens"
	"60321/pkg/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Register(context *gin.Context) {
	var request requests.RegisterRequest
	if err := context.ShouldBindJSON(&request); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var user = &models.UserModel{
		Name:     request.Name,
		Phone:    request.Phone,
		Password: request.Password,
		ChinaID:  request.ChinaID,
		Role:     int(request.Role),
	}
	bornTime := utils.GetUserBirthday(user.ChinaID)
	user.Age = uint(utils.CalculateAge(bornTime))
	user.BornTime = bornTime.Format("2006-01-02") // 将出生日期转换为字符串

	if err := global.Db.Create(&user).Error; err != nil {
		context.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	context.JSON(http.StatusOK, gin.H{"user": user})
}
func Login(context *gin.Context) {
	var request requests.LoginRequest
	if err := context.ShouldBindJSON(&request); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var user = &models.UserModel{}
	if err := global.Db.Take(&user, "phone = ? and password = ?", request.Phone, request.Password).Error; err != nil {
		context.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	token, err := tokens.GenerateToken(user.Name, user.Phone)
	if err != nil {
		context.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	context.JSON(http.StatusOK, gin.H{"tokens": token, "user": user})
}
